﻿// <copyright file="ImageActionResult.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Core.Web.ActionResults
{
    using System;
    using System.IO;
    using System.Web;
    using System.Web.Mvc;

    public class ImageResult : ActionResult
    {
        public ImageResult()
        {
        }

        public byte[] ImageData
        {
            get;
            set;
        }

        public MemoryStream ImageStream
        {
            get;
            set;
        }

        public string MimeType
        {
            get;
            set;
        }

        public HttpCacheability Cacheability
        {
            get;
            set;
        }

        public string ETag
        {
            get;
            set;
        }

        public DateTime? Expires
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (this.ImageData == null && ImageStream == null)
            {
                throw new ArgumentNullException("ImageData or ImageStream");
            }

            if (string.IsNullOrEmpty(this.MimeType))
            {
                throw new ArgumentNullException("MimeType");
            }

            context.HttpContext.Response.ContentType = this.MimeType;

            if (!string.IsNullOrEmpty(this.ETag))
            {
                context.HttpContext.Response.Cache.SetETag(this.ETag);
            }

            if (this.Expires.HasValue)
            {
                context.HttpContext.Response.Cache.SetCacheability(this.Cacheability);
                context.HttpContext.Response.Cache.SetExpires(this.Expires.Value);
            }

            if (ImageStream != null)
            {
                ImageData = ImageStream.ToArray();
            }

            context.HttpContext.Response.OutputStream.Write(this.ImageData, 0, this.ImageData.Length);

        }
    }
}